package model.commands;

import java.awt.Robot;
import java.util.ArrayList;
import java.util.List;

public abstract class AbstractCompositeCommand extends AbstractCommand implements CompositeCommand {
	private List<Command> commands = new ArrayList<Command>();

	@Override
	public void addCommand(Command cmd) {
		commands.add(cmd);
	}

	@Override
	public void addCommands(List<Command> commands) {
		commands.addAll(commands);
	}
	
	@Override
	public List<Command> getCommands() {
		return commands;
	}
	
	@Override
	public void execute() {
		resetRunningVariables();
		executeInnerCommands();
		propertyChangeSupport.firePropertyChange(EXECUTION_FINISHED, null, this); 
	}
	
	protected void executeInnerCommands() {
		for(Command cmd : getCommands()){
			while(pause && !stop){
				synchronized (this) {
					try {
						wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
			if(stop){
				break;
			}
			cmd.execute();
		}
	}
	
	@Override
	public void setRobot(Robot robot) {
		this.robot = robot;
		for(Command cmd: commands){
			cmd.setRobot(robot);
		}
	}
	
	@Override
	public synchronized void stop() {
		for(Command cmd: commands){
			cmd.stop();
		}
		super.stop();
	}
	
	@Override
	public synchronized void pause() {
		for(Command cmd: commands){
			cmd.pause();
		}
		super.pause();
	}
	
	@Override
	public synchronized void resume() {
		for(Command cmd: commands){
			cmd.resume();
		}
		super.resume();
	}

	@Override
	public void resetRunningVariables(){
		for(Command cmd: commands){
			cmd.resetRunningVariables();
		}
		super.resetRunningVariables();
	}
	
}
